// 引入模块
const http = require('http')
const fs = require('fs')
const template = require('art-template')

const server = http.createServer()

server.on('request', (req, res) => {

    // 获取客户端 URL
    const url = req.url

    if(url === '/') {
        // 读取模板文件
        fs.readFile('./tpl.html', (err, data) => {
            if (err) console.log('读取文件失败：' + error)

            const html = template.render(data.toString(), {
                name: 'Jack',
                age: 18,
                province: '山东省',
                hobbies: [
                    '写代码',
                    '唱歌',
                    '游泳'
                ]
            })

            console.log(html)

            res.setHeader('Content-Type', 'text/html; charset=utf-8')
            res.end(html)
        })
    } else {
        res.setHeader('Content-Type', 'text/html; charset=utf-8')
        res.end('<h2>404 Not Found</h2>')
    }
})

server.listen(3000, () => {
    console.log('Server running at port 3000')
})